package com.collectplus.express.parcel;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Message;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;

import com.collectplus.express.BaseActivity2;
import com.collectplus.express.R;
import com.collectplus.express.logic.AppHttp;
import com.collectplus.express.logic.AppResult;
import com.collectplus.express.logic.DialogMgr;
import com.collectplus.express.logic.JSON;
import com.collectplus.express.logic.MsgID;
import com.collectplus.express.model.IdCardInfoBean;
import com.collectplus.express.model.ParcelDetailBean;
import com.collectplus.express.passport.NewPassportDialogActivity;

import java.util.Iterator;

import droid.frame.ui.dialog.AppDialog;

/**
 * 核对包裹信息
 *
 * @author coffee<br>
 *         2016-11-30下午2:32:34
 */
public class ParcelCheckActivity extends BaseActivity2 implements OnClickListener {

    private ListView mListView;
    private ParcelCheckAdapter mAdapter;
    // 包裹数量
    private TextView mParcelCount;
    // 全选
    private CheckBox mCheckButton;
    private Button mSubmit;
    //
    private String stationId;

    private boolean isAuthentication = false;//身份认证是否通过  false没有  true 通过
    private IdCardInfoBean cardInfoBean = null;//身份认证相关信息

    @Override
    @SuppressLint("ResourceAsColor")
    protected void onCreate(Bundle savedInstanceState) {
        stationId = getIntent().getStringExtra("id");
        super.onCreate(savedInstanceState);
        showLoadingDialog(null);
        AppHttp.getInstance().stationGetAllParcels();
        AppHttp.getInstance().queryIDCardInfo(1);
    }

    @Override
    protected void findViewById() {
        setContentView(R.layout.parcel_check);
        super.findViewById();
        getAppTitle().setCommonTitle("核对包裹信息");
        mListView = (ListView) findViewById(R.id.listview);
        mAdapter = new ParcelCheckAdapter(null, getContext(), mListView);
        mParcelCount = (TextView) findViewById(R.id.parcel_check_count);
        //
        mCheckButton = (CheckBox) findViewById(R.id.parcel_check);
        mCheckButton.setOnClickListener(this);
        mSubmit = (Button) findViewById(R.id.parcel_submit);
        mSubmit.setOnClickListener(this);

        mListView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (mAdapter.isEmpty()) {
                    return;
                }
                ParcelDetailBean item = (ParcelDetailBean) parent.getItemAtPosition(position);
                mAdapter.setChecked(item.getId());
                //
                updateCount();
            }
        });
    }

    private void updateCount() {
        int count = mAdapter.getCheckIds().size();
        if (mAdapter.getItems().size() == count) {
            mCheckButton.setChecked(true);
        } else {
            mCheckButton.setChecked(false);
        }
        if (count == 0) {
            setButtonEnableStyle(mSubmit, false);
        } else {
            setButtonEnableStyle(mSubmit, true);
        }
        String format = "已选择" + count + "个包裹";
        SpannableString ss = new SpannableString(format);
        ss.setSpan(new ForegroundColorSpan(Color.parseColor("#306CF2")), 3, 4, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        mParcelCount.setText(ss);
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            // 查询当前用户的所有包裹
            case MsgID.station_getalls:
                cancelLoadingDialog();
                final AppResult<ParcelDetailBean> result = JSON.parseList(msg.obj, ParcelDetailBean.class);
                if (result.isSuccess()) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (result.getResultList().isEmpty()) {
                                findViewById(R.id.parcel_check_top_tip).setVisibility(View.GONE);
                                ((ViewGroup) mSubmit.getParent()).setVisibility(View.GONE);
                                findViewById(R.id.empty_bg).setVisibility(View.VISIBLE);
                            } else {
                                findViewById(R.id.empty_bg).setVisibility(View.GONE);
                                if (mListView.getAdapter() == null) {
                                    mListView.setAdapter(mAdapter);
                                }
                                mAdapter.setItems(result.getResultList(), true);
                                // 默认全部选中
                                mCheckButton.setChecked(true);
                                // update
                                onClick(mCheckButton);
                            }
                        }
                    });
                } else {
                    showToast(result.getMessage());
                }
                return true;
            // 投递包裹 -- 注意返回false
            case MsgID.station_post:
                final AppResult<?> result2 = JSON.parser(msg.obj);
                if (result2.isSuccess()) {
                    for (Iterator<ParcelDetailBean> it = mAdapter.getItems().iterator(); it.hasNext(); ) {
                        ParcelDetailBean item = it.next();
                        if (mAdapter.getCheckIds().contains(item.getId())) {
                            it.remove();
                        }
                    }
                    mAdapter.getCheckIds().clear();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            setButtonEnableStyle(mSubmit, false);
                            mAdapter.notifyDataSetChanged();
                            updateCount();
                            if (isAuthentication) {
                                showToast("投递成功");
                            } else {
                                DialogMgr.showAuthenticationTips(getContext(), mAdapter.isEmpty(), cardInfoBean);
                            }
                        }
                    });
                } else {
                    showToast(result2.getMessage());
                }
                return false;
            //身份认证信息查询
            case MsgID.query_idCard_info:
                if (1 != msg.arg1) {
                    return false;
                }
                final AppResult<IdCardInfoBean> appResult = JSON.parser(msg.obj, IdCardInfoBean.class);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (appResult.isSuccess()) {
                            cardInfoBean = appResult.getResult();
                            if (null == cardInfoBean) {
                                isAuthentication = false;
                            } else {
                                if (cardInfoBean.getStatus() >= 1 && cardInfoBean.getStatus() < 20) {
                                    isAuthentication = true;
                                } else {
                                    isAuthentication = false;
                                }
                            }
                        } else {
                            showToast(appResult.getMessage());
                        }
                    }
                });
                return false;
            default:
                return super.handleMessage(msg);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            // 全选|取消
            case R.id.parcel_check:
                CheckBox check = (CheckBox) v;
                // 当前选中
                mAdapter.checkAlls(check.isChecked());
                updateCount();
                break;
            case R.id.parcel_submit:
                int count = mAdapter.getCheckIds().size();
                if (count == 0) {
                    // showToast("请选择要投递的包裹");
                    return;
                }
                final AppDialog dialog = new AppDialog(getContext());
                dialog.setContent("是否将" + count + "个包裹投递到驿站中?");
                dialog.setCancelClickListener("取消", null);
                dialog.setConfirmClickListener("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                        AppHttp.getInstance().stationPost(mAdapter.getCheckIds().toString(), stationId);
                    }
                });
                dialog.show();
                break;
        }
    }

    @Override
    public void finish() {
        super.finish();
        if (NewPassportDialogActivity.getInstance() != null) {
            NewPassportDialogActivity.getInstance().finish();
        }
    }
}
